# from threading import Thread
# from threading import Lock
# import time
#
# lock_A = Lock()
# lock_B = Lock()
#
#
# class MyThread(Thread):
#
#     def run(self):
#         self.f1()
#         self.f2()
#
#
#     def f1(self):
#
#         lock_A.acquire()
#         print(f'{self.name}拿到了A锁')
#
#         lock_B.acquire()
#         print(f'{self.name}拿到了B锁')
#
#         lock_B.release()
#
#         lock_A.release()
#
#     def f2(self):
#
#         lock_B.acquire()
#         print(f'{self.name}拿到了B锁')
#
#         time.sleep(0.1)
#         lock_A.acquire()
#         print(f'{self.name}拿到了A锁')
#
#         lock_A.release()
#
#         lock_B.release()
#
#
#
# if __name__ == '__main__':
#
#     for i in range(3):
#         t = MyThread()
#         t.start()



from threading import Thread
from threading import RLock
import time

lock_A = lock_B = RLock()

# 递归锁有一个计数的功能, 原数字为0,上一次锁,计数+1,释放一次锁,计数-1,
# 只要递归锁上面的数字不为零,其他线程就不能抢锁.
class MyThread(Thread):

    def run(self):
        self.f1()
        self.f2()


    def f1(self):

        lock_A.acquire()
        print(f'{self.name}拿到了A锁')

        lock_B.acquire()
        print(f'{self.name}拿到了B锁')

        lock_B.release()

        lock_A.release()

    def f2(self):

        lock_B.acquire()
        print(f'{self.name}拿到了B锁')

        time.sleep(0.1)
        lock_A.acquire()
        print(f'{self.name}拿到了A锁')

        lock_A.release()

        lock_B.release()



if __name__ == '__main__':

    for i in range(3):
        t = MyThread()
        t.start()